const TokenKey = 'satoken'
const PermissionKey = 'permission'
export function getToken() {
  return localStorage.getItem(TokenKey);
}

export function setToken(token) {
  return localStorage.setItem(TokenKey,token);
}

export function removeToken() {
  return localStorage.removeItem(TokenKey);
}

export function getPermission() {
  return localStorage.getItem(PermissionKey);
}

export function setPermission(permission) {
  return localStorage.setItem(PermissionKey,permission);
}

export function removePermission() {
  return localStorage.removeItem(PermissionKey);
}

export function hasPermission(permission) {
  const userPermissions = getPermission();
  // 检查权限是否直接存在
  if (userPermissions.includes(permission)) {
    return true;
  }

  // 拆分权限字符串
  const [resource, action] = permission.split('.');

  // 检查通配符权限
  if (action) {
    const resourceWildcard = `${resource}.*`;
    const actionWildcard = `*.${action}`;
    const anyWildcard = '*.*';

    if (
      userPermissions.includes(resourceWildcard) ||
      userPermissions.includes(actionWildcard) ||
      userPermissions.includes(anyWildcard)
    ) {
      return true;
    }

    // 特殊处理以 select, add, update, delete 结尾的权限
    const specialActions = ['select', 'add', 'update', 'delete'];
    if (specialActions.includes(action)) {
      const anyResourceAction = `*.${action}`;
      if (userPermissions.includes(anyResourceAction)) {
        return true;
      }
    }
  }

  return false;
}